package com.jingbit.ai.helper;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Reminders;

import com.jingbit.ai.entities.ScheduleInfo;

import java.util.Calendar;
import java.util.TimeZone;

/**
 * 日程安排工具类
 * 
 * @author pansha
 *
 */
@SuppressLint({ "InlinedApi", "NewApi" })
public class ScheduleHelper {
	private static final String TAG = "ScheduleHelper";

	private static String calanderURL;
	private static String calanderEventURL;
	private static String calanderRemiderURL;

	private static Context context;

	@SuppressLint("NewApi")
	public static void initScheduleHelper(Context context) {
		ScheduleHelper.context = context;
		// 为了兼容不同版本的日历,2.2以后url发生改变
		if (Build.VERSION.SDK_INT >= 8) {
			calanderURL = "content://com.android.calendar/calendars";
			calanderEventURL = "content://com.android.calendar/events";
			calanderRemiderURL = "content://com.android.calendar/reminders";

		} else {
			calanderURL = "content://calendar/calendars";
			calanderEventURL = "content://calendar/events";
			calanderRemiderURL = "content://calendar/reminders";
		}
	}

	public static long addSchedule(ScheduleInfo scheduleInfo) {
		// 添加一个条目到特定的日历，我们需要配置一个日历项插入使用与ContentValues如下：
		ContentValues event = new ContentValues();
		// 事件插入日历标识符
		event.put("calendar_id", scheduleInfo.getId());

		// 活动的标题，描述和位置领域的一些基本信息。
		event.put("title", scheduleInfo.getTitle());
		event.put("description", scheduleInfo.getDesc());
		event.put("eventLocation", scheduleInfo.getLocation());

		// 设置事件的开始和结束的信息如下
		event.put("dtstart", scheduleInfo.getStart());
		event.put("dtend", scheduleInfo.getEnd());

		// 设置一个全天事件的条目
		event.put("allDay", scheduleInfo.getAllDay()); // 0 for false, 1 for
														// true

		// 事件状态暂定(0)，确认(1)或取消(2)
		event.put("eventStatus", scheduleInfo.getStatus());

		// 控制是否事件触发报警，提醒如下
		event.put("hasAlarm", 1); // 0 for false, 1 for
															// true

		// 设置时区,否则会报错
		event.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());

		// 一旦日历事件配置正确，我们已经准备好使用ContentResolver插入到相应的开放新日历的日历事件项：
		Uri eventsUri = Uri.parse(calanderEventURL);
		Uri newEvent = context.getContentResolver().insert(eventsUri, event);

		// 设置什么时候提醒
		long id = Long.parseLong(newEvent.getLastPathSegment());
		ContentValues values = new ContentValues();
		values.put("event_id", id);
		values.put("method", Reminders.METHOD_ALERT);

		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(scheduleInfo.getEnd());

		int year = calendar.get(Calendar.YEAR);
		int mon = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);

		String sMon = mon < 10 ? "0" + mon : mon + "";
		String sDay = day < 10 ? "0" + day : day + "";

		String rrule = null;
		if (scheduleInfo.isBirthday()) {
			Calendar calendar1 = Calendar.getInstance();
			calendar1.setTimeInMillis(scheduleInfo.getStart());
			int mon1 = calendar1.get(Calendar.MONTH) + 1;
			int day1 = calendar1.get(Calendar.DAY_OF_MONTH);
			String sMon1 = mon1 < 10 ? "0" + mon1 : mon1 + "";
			String sDay1 = day1 < 10 ? "0" + day1 : day1 + "";
			rrule = "FREQ=YEARLY;BYMONTH=" + sMon1 + ";BYMONTHDAY=" + sDay1;
		} else {
			rrule = getRule(scheduleInfo.getRepeat());
		}
		if (rrule != null) {
			if (scheduleInfo.getRepeat() > 3) {
				rrule = ";UNTIL=" + year + sMon + sDay + "T000000Z";
			}
			values.put("rrule", rrule);
		}
		// 提前10分钟有提醒
		values.put("minutes", getAlarm(scheduleInfo.getRemind()));
		Uri ret = context.getContentResolver().insert(Reminders.CONTENT_URI, values);
		return ContentUris.parseId(ret);
	}

	private static String getRule(int repeat) {
		String rrule = null;
		switch (repeat) {
		case 1:// 5次
			rrule = "FREQ=MINUTELY;COUNT=5";
		case 2:// 10次
			rrule = "FREQ=MINUTELY;COUNT=10";
		case 3:// 15次
			rrule = "FREQ=MINUTELY;COUNT=15";
		case 4:// 每半小时
			rrule = "FREQ=MINUTELY;INTERVAL=30";
			break;
		case 5:// 每小时
			rrule = "FREQ=MINUTELY;INTERVAL=60";
			break;
		case 6:// 每1天
			rrule = "FREQ=DAILY";
			break;
		case 7:// 每3天
			rrule = "FREQ=DAILY;INTERVAL=3";
			break;
		case 8:// 每周一
			rrule = "FREQ=WEEKLY";
			break;
		case 9:// 每半月
			rrule = "FREQ=MONTHLY;BYMONTHDAY=15";
			break;
		case 10:// 每月初
			rrule = "FREQ=MONTHLY;BYMONTHDAY=1";
			break;
		case 11:// 每季初
			rrule = "FREQ=MONTHLY;INTERVAL=3";
			break;
		case 12:// 每半年
			rrule = "FREQ=YEARLY;BYMONTH=7;BYMONTHDAY=1";
			break;
		case 13:// 每年初
			rrule = "FREQ=YEARLY;BYMONTH=1;BYMONTHDAY=1";
			break;
		default:// 仅一次
		}
		return rrule;
	}

	private static int getAlarm(int alarm) {
		switch (alarm) {
		case 1:
			return 5;
		case 2:
			return 15;
		case 3:
			return 30;
		case 4:
			return 60;
		case 5:
			return 120;
		case 6:
			return 60 * 24;
		case 7:
			return 60 * 24 * 5;
		case 8:
			return 60 * 24 * 15;
		case 9:
			return 60 * 24 * 30;
		default:
			return 0;
		}
	}

	/**
	 * 删除所有的事件
	 * 
	 */
	public static void delAllEvents() {
		String calanderEventURL = "";
		if (Build.VERSION.SDK_INT >= 8) {
			calanderEventURL = "content://com.android.calendar/events";
		} else {
			calanderEventURL = "content://calendar/events";
		}

		ContentResolver cre = context.getContentResolver();
		int cure = cre.delete(Uri.parse(calanderEventURL), null, null);
		Logger.log(TAG, "del events lines ==>" + cure);

	}

	/**
	 * 删除指定id的事件
	 * 
	 * @param id
	 */
	public static void deleteEventById(String id) {
		String calanderEventURL = "";
		if (Build.VERSION.SDK_INT >= 8) {
			calanderEventURL = "content://com.android.calendar/events";
		} else {
			calanderEventURL = "content://calendar/events";
		}

		ContentResolver cre = context.getContentResolver();
		int cure = cre.delete(Uri.parse(calanderEventURL), "_id=?", new String[] { id });
		Logger.log(TAG, "del events lines ==>" + cure);
	}

}
